import React, { ReactElement } from 'react';
import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { routes, BreadcrumbRoute } from '../../config/breadcrumbConfig';
import './PageBreadcrumb.scss';

interface BreadcrumbItem {
  key: string;
  title: ReactElement;
}

const PageBreadcrumb: React.FC = () => {
  const location = useLocation();
  const pathSnippets = location.pathname.split('/').filter(i => i);

  const getBreadcrumbItem = (path: string): BreadcrumbRoute | undefined => {
    for (const route of routes) {
      if (route.path === `/${path}`) {
        return route;
      }
      if (route.children) {
        for (const child of route.children) {
          const dynamicPath = child.path.split('/').pop();
          const currentPath = `/${path}`;
          if (dynamicPath?.startsWith(':') && child.path.startsWith(route.path)) {
            return {
              ...child,
              breadcrumbName: document.title.split(' - ').pop() || child.breadcrumbName
            };
          }
          if (child.path === currentPath) {
            return child;
          }
        }
      }
    }
    return undefined;
  };

  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
    const item = getBreadcrumbItem(pathSnippets.slice(0, index + 1).join('/'));
    
    if (!item) return null;

    const IconComponent = item.icon;

    return {
      key: url,
      title: (
        <Link to={url}>
          {IconComponent && <IconComponent style={{ marginRight: 4 }} />}
          {item.breadcrumbName}
        </Link>
      ),
    };
  }).filter((item): item is BreadcrumbItem => item !== null);

  const HomeIcon = routes[0].icon;

  const breadcrumbItems = [
    {
      key: '/',
      title: (
        <Link to="/">
          <HomeIcon style={{ marginRight: 4 }} />
          {routes[0].breadcrumbName}
        </Link>
      ),
    },
    ...extraBreadcrumbItems,
  ];

  return (
    <div className="page-breadcrumb">
      <Breadcrumb items={breadcrumbItems} />
    </div>
  );
};

export default PageBreadcrumb; 